package com.zhufeng.gateway.db.route;

import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.handler.predicate.AbstractRoutePredicateFactory;
import org.springframework.cloud.gateway.handler.predicate.GatewayPredicate;
import org.springframework.stereotype.Component;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.server.ServerWebExchange;

import java.util.Arrays;
import java.util.List;
import java.util.function.Predicate;

/**
 * @ClassName: ZhufengVersionRoutePredicateFactory
 * @Description 动态路由版本判断
 * @author 月夜烛峰
 * @date 2022/9/15 16:49
 */
@Slf4j
@Component
public class ZhufengVersionRoutePredicateFactory extends AbstractRoutePredicateFactory<ZhufengVersionRoutePredicateFactory.Config> {

    public static final String VERSION_KEY = "version";

    public ZhufengVersionRoutePredicateFactory() {
        super(Config.class);
    }

    @Override
    public List<String> shortcutFieldOrder() {
        return Arrays.asList(VERSION_KEY);
    }

    @Override
    public Predicate<ServerWebExchange> apply(Config config) {

        return new GatewayPredicate() {
            @Override
            public boolean test(ServerWebExchange exchange) {
                String version = exchange.getRequest().getHeaders().getFirst("version");
                log.info("系统版本:{},当前请求版本:{}", config.version, version);
                if (config.version == null || config.version.length() == 0) {
                    log.info("默认不拦截...");
                    return true;
                }

                if (version == null || version.length() == 0) {
                    log.info("header中版本为空,不拦截...");
                    return true;
                }
                if (config.version.equals(version)) {
                    log.info("校验通过，请求放行!当前请求版本:{},系统要求版本:{}", version, config.version);
                    return true;
                }
                return false;
            }

            @Override
            public String toString() {
                return String.format("version: %s", config.version);
            }
        };
    }

    @Validated
    public static class Config {


        private String version;

        public String getVersion() {
            return version;
        }

        public void setVersion(String version) {
            this.version = version;
        }


    }

}